import os
import mutagen
from mutagen.mp3 import MP3
from mutagen.flac import FLAC
from mutagen.wavpack import WavPack
from mutagen.oggvorbis import OggVorbis


class AudioProcessor:
    """音频处理器，负责音频文件信息的获取和处理"""
    
    # 支持的音频文件扩展名
    SUPPORTED_AUDIO_EXTENSIONS = ['.mp3', '.flac', '.wav', '.ogg', '.wma', '.m4a']
    
    @staticmethod
    def is_audio_file(file_path):
        """检查文件是否为支持的音频文件"""
        _, ext = os.path.splitext(file_path)
        return ext.lower() in AudioProcessor.SUPPORTED_AUDIO_EXTENSIONS
    
    @staticmethod
    def get_audio_info(file_path):
        """获取音频文件的信息"""
        info = {
            'artist': '',
            'title': '',
            'duration': 0
        }
        
        try:
            # 使用mutagen库获取音频信息
            audio = mutagen.File(file_path)
            if audio:
                # 获取时长
                info['duration'] = audio.info.length
                
                # 尝试获取艺术家和标题信息
                if hasattr(audio, 'tags') and audio.tags:
                    # 针对不同格式尝试不同的标签字段
                    if 'TPE1' in audio.tags:  # MP3 ID3v2
                        info['artist'] = audio.tags['TPE1'].text[0]
                    elif 'artist' in audio.tags:  # 通用
                        info['artist'] = audio.tags['artist'][0]
                    
                    if 'TIT2' in audio.tags:  # MP3 ID3v2
                        info['title'] = audio.tags['TIT2'].text[0]
                    elif 'title' in audio.tags:  # 通用
                        info['title'] = audio.tags['title'][0]
        except:
            pass
        
        # 如果没有获取到标题，使用文件名
        if not info['title']:
            info['title'] = os.path.splitext(os.path.basename(file_path))[0]
        
        return info
    
    @staticmethod
    def scan_directory_for_audio(directory_path):
        """扫描目录及其子目录中的所有音频文件"""
        audio_files = []
        
        for root, _, files in os.walk(directory_path):
            for file in files:
                file_path = os.path.join(root, file)
                if AudioProcessor.is_audio_file(file_path):
                    audio_files.append(file_path)
        
        return audio_files